<template>
	<view class="gl-container">
		<swiper :current="current" :disable-touch="true" :style="{height: topH+'px'}">
			<swiper-item>
				<uni-card :title="title">
					<template v-slot:title>
						<view class="gl-header">
							<view class="gl-header-left">
								<uni-search-bar v-model="search" placeholder="关键字搜索" cancelButton="none"
									bgColor="#f1f1f1" @confirm="refresh"></uni-search-bar>
								<uni-data-picker v-model="curMode" placeholder="查询所有分类" :localdata="maxModeData"
									:map="{text:'name',value:'id'}" @change="EventMode"
									style="width: 240px;"></uni-data-picker>
								<uni-data-picker v-model="curPlace" placeholder="查询所有商户" :localdata="placeArray"
									:map="{text:'nicename',value:'id'}" @change="EventPlace"
									style="width: 240px;"></uni-data-picker>
								<checkbox-group style="font-size: small;color: #6a6a6a;" @change="checkChange">
									<label>
										<checkbox value="status" :checked="checkData.includes('status')"
											style="transform:scale(0.7)" />状态
									</label>
									<label>
										<checkbox value="is_list" :checked="checkData.includes('is_list') "
											style="transform:scale(0.7)" />上架
									</label>
									<label>
										<checkbox value="is_share" :checked="checkData.includes('is_money') "
											style="transform:scale(0.7)" />隐藏虚拟产品
									</label>
								</checkbox-group>
							</view>
							<view class="gl-header-right">
								<view class="gl-button gl-button-success" @tap="EventButtonNew()">
									<uni-icons type="folder-add" size="18" color="#fff"></uni-icons>
									<text style="font-size: small;">新增</text>
								</view>
								<view class="gl-button gl-button-base" hover-class="button-base-hover"
									:hover-stay-time="100" @click="refresh">
									<uni-icons type="reload" size="18" color="#fff"></uni-icons>
									<text style="font-size: small;">刷新</text>
								</view>
							</view>
						</view>
					</template>

					<view class="gl-body table-container" style="background-color: #f8f8f8;font-size: x-small;"
						:style="{height:swiperH+'px'}">
						<uni-table emptyText="暂无更多数据">
							<uni-tr class="table-head">
								<uni-th align="center" width="30">ID</uni-th>
								<uni-th>名称</uni-th>
								<uni-th>分类</uni-th>
								<uni-th>商户</uni-th>
								<uni-th>累计销量</uni-th>
								<uni-th>最低销售价</uni-th>
								<uni-th>最低结算价</uni-th>
								<uni-th>排序</uni-th>
								<uni-th width="40">状态</uni-th>
								<uni-th width="40">上架</uni-th>
								<uni-th width="40">实物</uni-th>
								<uni-th>供应链</uni-th>
								<uni-th>操作</uni-th>
							</uni-tr>
							<uni-tr v-for="(item, index) in spuArray" :key="index">
								<uni-td align="center" width="30">{{item.id}}</uni-td>
								<uni-td>
									<view style="display: flex;align-items: center;gap: 5px;position: relative;"
										@tap="EventButtonView(item)">
										<image :src="sConf.cos + (item.face ??'/media/default/cover.png')"
											mode="widthFix" style="width: 96px;border-radius: 5px;"></image>
										<text class="gl-title-item"
											style="font-weight: bold;max-width: 240px;">{{item.name}}</text>
										<view v-if="item.has_isoat" style="position: absolute; left: 5px;bottom: 0;">
											<image :src="sConf.cos + '/media/v2/yxiso/yx_6.png'" mode=""
												style="width: 40px;height: 32px; ">
											</image>
										</view>
									</view>
								</uni-td>
								<uni-td>{{item.max_mode?.name ?? '无'}} -> {{item.min_mode?.name ?? '无'}}</uni-td>
								<uni-td>{{item.pid_place?.nicename ?? '无'}}</uni-td>
								<uni-td>{{calaSumHot(item.specs)}}</uni-td>
								<uni-td>{{calaMinMoney(item.specs)}}</uni-td>
								<uni-td>{{calaMinPrice(item.specs)}}</uni-td>
								<uni-td><uni-number-box :value="item.hot" :min="0" :step="1"
										@change="(event)=>{ EventHotChange(event, item.id)}"></uni-number-box></uni-td>
								<uni-td>
									<switch :checked="Boolean(item.status)" style="transform:scale(0.5)"
										:disabled="Boolean(item.spu)"
										@change="event => EventStateChange(event, item.id)" />
								</uni-td><uni-td>
									<switch :checked="Boolean(item.is_list)" style="transform:scale(0.5)"
										@change="event=>EventListChange(event,item.id)" />
								</uni-td><uni-td>
									<switch :checked="Boolean(item.is_money)" style="transform:scale(0.5)"
										@change="event=>EventShowChange(event,item.id)" />
								</uni-td>
								<uni-td>
									{{item.spu}}
								</uni-td>
								<uni-td>
									<view style="display: flex;gap: 5px;">
										<text style="color: #007aff;font-size: small;"
											@tap="EventButtonView(item)">详情</text>
										<text v-if="item.spu" class="gl-link-warning"
											@tap="showRemoteSpu(item.spu)">远程</text>
										<text v-else-if="item.id===9"></text>	
										<text v-else class="gl-link-error" @tap="showRemoveSpu(item)">删除</text>
									</view>
								</uni-td>
							</uni-tr>
						</uni-table>
					</view>

					<template v-slot:actions>
						<view class="gl-footer">
							<uni-pagination :show-icon="true" :total="count" :pageSize="size" v-model="page" title="翻页"
								@change="refresh" />
						</view>
					</template>
				</uni-card>
			</swiper-item>
			<swiper-item>
				<uni-card title="商品SPU" v-if="curSpuData">
					<template v-slot:title>
						<view class="gl-header">
							<view style="display: flex;align-items: center;">
								<uni-icons type="undo-filled" size="40" color="#4cd964" @click="current--"
									style="padding: 3px;border-radius: 2px;"></uni-icons>
								<text>{{curSpuData.id}}</text>
								<text style="padding: 4px;">-</text>
								<text selectable style="font-weight: bold;">{{curSpuData.name}}</text>
							</view>
							<view class="">
								<view class="gl-button gl-button-base" hover-class="button-base-hover"
									:hover-stay-time="100" @click="loadSpuDataList(curSpuData.id)">
									<uni-icons type="reload" size="18" color="#fff"></uni-icons>
									<text style="font-size: small;">刷新</text>
								</view>
							</view>
						</view>
					</template>

					<view class="">
						<view style="display: flex; ">
							<view class="ui-all"
								style="display: flex;flex-direction: column;gap: 10px;padding: 0 10px;position: relative;">
								<image :src="sConf.cos + (curSpuData?.face || '/media/default/cover.png')" mode=""
									@click="changeCover" style="width: 128px;height: 128px;border-radius: 5px;"></image>
								<view v-if="curSpuData.has_isoat"
									style="position: absolute; left: 5px;bottom: 0;padding: 10px;">
									<image :src="sConf.cos + '/media/v2/yxiso/yx_6.png'" mode=""
										style="width: 40px;height: 32px; ">
									</image>
								</view>
							</view>
							<view class="ui-all" style="display: flex;flex-direction: column;gap: 10px;">
								<view class="" style="display: flex;gap: 20px;width: 100%;">
									<view class="ui-list"
										style="display: flex;align-items: center;gap: 10px;width: 100%;">
										<text style="font-weight: bold;">产品名称:</text>
										<uni-easyinput v-model="curSpuData.name" trim="all"
											@confirm="spuNameChange"></uni-easyinput>
									</view>
								</view>
								<view class="" style="display: flex;gap: 20px;">
									<view class="ui-list" style="display: flex;align-items: center;gap: 10px;">
										<uni-data-select v-model="curSpuData.modep" :localdata="maxModeData"
											emptyTips="没有" label="选择大类" placeholder="所有大类" style="width: 240px;"
											@change="maxModeChange"></uni-data-select>
									</view>
									<view class="ui-list" style="display: flex;align-items: center;gap: 10px;">
										<uni-data-select v-model="curSpuData.mode" :localdata="minModeData"
											emptyTips="没有" label="选择小类" placeholder="所有小类" style="width: 280px;"
											@change="minModeChange"></uni-data-select>
									</view>
									<view class="ui-list" style="display: flex;align-items: center;gap: 10px;">
										<uni-data-select v-model="curSpuData.pid" :localdata="placeArray" emptyTips="没有"
											label="选择商户" placeholder="所有商户" style="width: 240px;"
											@change="placeChange"></uni-data-select>
									</view>
								</view>
								<view class="" style="display: flex;gap: 20px;">
									<view class="ui-list"
										style="display: flex;align-items: center;gap: 10px;width: 100%;">
										<text style="font-weight: bold;">创建时间:</text>
										<text>{{curSpuData?.create}}</text>
									</view>
									<view class="ui-list"
										style="display: flex;align-items: center;gap: 10px;width: 100%;">
										<text style="font-weight: bold;">上次修改:</text>
										<text>{{curSpuData?.lasttime}}</text>
									</view>
									<view class="ui-list" v-if="curSpuData?.spu"
										style="display: flex;align-items: center;gap: 10px;width: 100%;">
										<text style="font-weight: bold;">供应链SPU:</text>
										<text selectable="">{{curSpuData?.spu}}</text>
									</view>
								</view>
							</view>
						</view>
						<view style="padding-top: 10px;">
							<uni-segmented-control :current="currentControl" :values="menuData"
								@clickItem="currentControlChange"></uni-segmented-control>
						</view>
						<view class="">
							<productTextCard v-if="currentControl === 0" :depict="curSpuData?.jingle"
								@reload="loadSpuDataList(curSpuData.id)">
							</productTextCard>
							<productTagsCard v-if="currentControl === 1" :data="curSpuData?.tag" :pid="curSpuData?.pid"
								:gid="curSpuData?.id" @reload="loadSpuDataList(curSpuData.id)"></productTagsCard>
							<productArgsCard v-if="currentControl === 2" :data="curSpuData?.args" :pid="curSpuData?.pid"
								:gid="curSpuData?.id" @reload="loadSpuDataList(curSpuData.id)"></productArgsCard>
							<productPicsCard v-if="currentControl === 3" :data="curSpuData?.all_media"
								:pid="curSpuData?.pid" :gid="curSpuData?.id" @reload="loadSpuDataList(curSpuData.id)">
							</productPicsCard>
							<productSku2Card v-if="currentControl === 4" :data="curSpuData?.specs"
								:pid="curSpuData?.pid" :gid="curSpuData?.id" @reload="loadSpuDataList(curSpuData.id)"
								@tosku="swiperSKU">
							</productSku2Card>
						</view>
					</view>
					<view class="" style="height: 30vh;">
						<!-- 产品封面上传 -->
						<cos-multiple-post ref="cosCover" :host="sConf.host" :token="sConf.auth.token" path="product"
							onHide once @upFinish="EventFinish"></cos-multiple-post>
					</view>
				</uni-card>
			</swiper-item>
			<swiper-item>
				<productSkuAttrCard ref="productSkuAttr" :data="curSkuData" isback
					@toback="current--; loadSpuDataList(curSpuData.id)" />
			</swiper-item>
		</swiper>

		<popRemoteSpuVue ref="popRemoteSpu"></popRemoteSpuVue>
	</view>
</template>

<script>
	import psMethod from '@/common/psMethod';
	import popRemoteSpuVue from './pop-remote-spu.vue';

	import productTextCard from '@/components/sub-product/docs-card.vue'
	import productTagsCard from '@/components/sub-product/tags-card.vue'
	import productArgsCard from '@/components/sub-product/args-card.vue'
	import productPicsCard from '@/components/sub-product/image-card.vue'
	import productSku2Card from '@/components/sub-product/sku2-card.vue'
	import productSkuAttrCard from '@/components/sub-product/sku-attr.vue'
	export default {
		data() {
			return {
				topH: 0,
				swiperH: 0,
				count: 0, // 记录数
				size: 50, // 页大小
				page: 1, // 当前页					
				title: 'SPU商品列表',
				sConf: getApp().globalData,
				current: 0,
				currentControl: 0,
				spuArray: [],
				search: null,
				modeArray: [],
				curMode: null,
				placeArray: [],
				curPlace: null,
				checkData: ['status', 'is_list', 'is_money'], // 单选项目
				menuData: ['文案', '标签', '参数', '图库', '规格'], // spu属性

				// 详情页
				curSpuData: null,
				maxModeData: [],
				minModeData: [],

				// SKU
				curSkuData: null
			}
		},
		mounted() {
			console.log('...mounted...');
			this.designLayout()
			this.loadModeList()
			this.loadPlaceList()
			this.refresh()
		},
		components: {
			popRemoteSpuVue,
			productTextCard,
			productTagsCard,
			productArgsCard,
			productPicsCard,
			productSku2Card,
			productSkuAttrCard
		},
		methods: {
			/**
			 * 编辑SKU
			 */
			swiperSKU(e) {
				this.curSkuData = e;
				this.current = 2
			},
			currentControlChange(e) {
				console.log('currentControlChange', e);
				this.currentControl = e.currentIndex
			},
			/**
			 * 上传封面
			 */
			changeCover() {
				this.$refs.cosCover.open()
			},
			EventFinish(e) {
				console.log('EventFinish', e);
				this.curSpuData.face = e[0];
				let data = {
					face: e[0]
				}
				this.EventDataChange(data, this.curSpuData.id)
			},
			/**
			 * 编辑名称
			 */
			spuNameChange(e) {
				console.log('spuNameChange', e);
				if (!e) {
					return
				}
				let old = this.filterSpu(this.curSpuData.id)
				if (old.name === e) {
					return
				}
				let that = this
				uni.showModal({
					title: '询问',
					content: '是否要修改商品名称?',
					success(r) {
						if (r.confirm) {
							let data = {
								name: e
							}
							that.EventDataChange(data, that.curSpuData.id)
						}
					}
				})
			},
			/**
			 * 编辑大类
			 */
			maxModeChange(e) {
				console.log('maxModeChange', e);
				this.curSpuData.mode = null
				this.loadModeList(e)
			},
			/**
			 * 编辑小类
			 */
			minModeChange(e) {
				console.log('minModeChange', e);
				if (!e) {
					return
				}
				let old = this.filterSpu(this.curSpuData.id)
				if (old.mode === e) {
					return
				}
				let that = this
				uni.showModal({
					title: '询问',
					content: '是否要修改商品分类?',
					success(r) {
						if (r.confirm) {
							let data = {
								mode: e,
								modep: that.curSpuData.modep
							}
							that.EventDataChange(data, that.curSpuData.id)
						}
					}
				})
			},
			/**
			 * 编辑商户
			 */
			placeChange(e) {
				console.log('placeChange', e);
				if (!e) {
					return
				}
				let old = this.filterSpu(this.curSpuData.id)
				if (old.pid === e) {
					return
				}
				let that = this
				uni.showModal({
					title: '询问',
					content: '是否要修改商品归属商户?',
					success(r) {
						if (r.confirm) {
							let data = {
								pid: e
							}
							that.EventDataChange(data, that.curSpuData.id)
						}
					}
				})
			},
			/**
			 * 查看详情SPU
			 */
			showRemoveSpu(e) {
				let that = this
				let token = this.sConf.auth.token || '';
				uni.showModal({
					title: '删除SPU',
					content: `是否要删该商品=>${e.name}`,
					success(r) {
						if (r.confirm) {
							psMethod.syncAuthenticatorRequest(`/admin/cargoBase/${e.id}/`, 'DELETE', token, {})
								.then(res => {
									that.refresh()
								})
						}
					}
				})
			},
			EventButtonView(e) {
				this.loadModeList(e.modep)
				this.curSpuData = JSON.parse(JSON.stringify(e))
				this.current = 1
			},
			filterSpu(e) {
				return this.spuArray.find(item => item.id === e)
			},
			checkChange(e) {
				this.checkData = e.detail.value
				this.refresh()
			},
			EventPlace(e) {
				console.log('EventPlace', this.curPlace);
				this.refresh()
			},
			EventMode(e) {
				console.log('EventMode', this.curMode, typeof(this.curMode));
				this.refresh()
			},
			EventButtonNew(e = null) {
				let that = this
				uni.showModal({
					title: "新的商品",
					placeholderText: "请输入新的商品名称",
					editable: true,
					success(r) {
						if (r.confirm) {

							let host = that.sConf.host + '/admin/cargoBase/';
							let token = that.sConf.auth.token || '';
							let data = {
								name: r.content
							}
							psMethod.syncAuthenticatorRequest('/admin/cargoBase/', 'POST', token, data).then(
								res => {
									console.log('创建商品', res);
									uni.showToast({
										title: '提交商品成功'
									})
									that.refresh()
								}).catch(err => {
								console.log('创建商品失败', err);
								uni.showModal({
									title: '失败',
									content: '创建商品失败',
									showCancel: false
								})
							})

						}
					}
				})
			},
			/**
			 * 查看远程信息
			 */
			showRemoteSpu(e) {
				this.$refs.popRemoteSpu.open(e)
			},
			/**
			 * 编辑其他信息
			 */
			EventDataChange(data, index) {
				let token = this.sConf.auth.token || '';
				psMethod.syncAuthenticatorRequest(`/admin/cargoBase/${index}/`, 'PATCH', token, data).then(res => {
					// uni.showToast({
					// 	title: '请求完成'
					// })
				}).catch(err => {
					uni.showToast({
						title: '请求失败'
					})
					this.refresh()
				})
			},
			/**
			 * 编辑排序
			 */
			EventHotChange(e, index) {
				console.log('EventHotChange', e, index);
				let data = {
					hot: e
				}
				this.EventDataChange(data, index)
			},
			/**
			 * 编辑显示状态
			 */
			EventShowChange(e, index) {
				console.log('EventShowChange', e.detail.value, index);
				let data = {
					is_money: e.detail.value ? 1 : 0
				}
				this.EventDataChange(data, index)
			},
			/**
			 * 编辑状态
			 */
			EventStateChange(e, index) {
				console.log('EventStateChange', e.detail.value, index);
				let data = {
					status: e.detail.value ? 1 : 0
				}
				this.EventDataChange(data, index)
			},
			/**
			 * 编辑上架状态
			 */
			EventListChange(e, index) {
				console.log('EventListChange', e.detail.value);
				let data = {
					is_list: e.detail.value ? 1 : 0
				}
				this.EventDataChange(data, index)
			},
			/**
			 * 计算真实销量
			 */
			calaSumHot(e) {
				let m = 0
				e.forEach(item => {
					m += Number(item.hot) ?? 0
				})
				return m
			},
			/**
			 * 计算最小卖价格
			 */
			calaMinMoney(e) {
				let m = 0
				e.forEach(item => {
					if (item.money < m || m === 0) {
						m = item.money
					}
				})
				return (m / 100).toFixed(2)
			},
			/**
			 * 计算最小结算价
			 */
			calaMinPrice(e) {
				let m = 0
				e.forEach(item => {
					if (item.price < m || m === 0) {
						m = item.price
					}
				})
				return (m / 100).toFixed(2)
			},
			refresh() {
				let host = this.sConf.host + '/admin/cargoList/';
				let token = this.sConf.auth.token || '';
				let data = {
					page: this.page,
					size: this.size,
					ordering: '-id'
				}
				if (this.search) {
					data.search = this.search
				}
				if (this.curMode) {
					data.mode = this.curMode
				}
				if (this.curPlace) {
					data.pid = this.curPlace
				}

				this.checkData.forEach(item => {
					data[item] = 1
				})

				// console.log('检查token', token);
				// console.log('查询参数', data);
				uni.showLoading({
					title: '加载中'
				})
				psMethod.syncAuthenticatorRequest('/admin/cargoList/', 'GET', token, data).then(res => {
					console.log('加载SPU列表', res);
					this.spuArray = res.resmsg
					this.count = res.count
					this.size = res.size
					// if (!this.curSpuData) {
					// 	let tmpData = this.filterSpu(this.curSpuData.id)
					// 	this.curSpuData = JSON.parse(JSON.stringify(tmpData))
					// }
				}).catch(err => {
					console.log('加载SPU列表失败', err);
					if (this.page > 1 && err.rescode === 404) {
						this.page--
					}
				}).finally(() => {
					uni.hideLoading()
				})
			},
			/**
			 * 加载spu
			 */
			loadSpuDataList(e) {
				console.log('loadSpuDataList', e);
				let token = this.sConf.auth.token || '';
				uni.showLoading({
					title: '加载中'
				})
				psMethod.syncAuthenticatorRequest(`/admin/cargoList/${e}/`,
					'GET', token, {}).then(res => {
					console.log('加载SPU列表', res);
					this.curSpuData = res.resmsg
				}).catch(err => {
					console.log('加载SPU列表失败', err);
					this.curSpuData = null
				}).finally(() => {
					uni.hideLoading()
				})
			},
			/**
			 * 加载商户列表
			 */
			loadPlaceList() {
				let token = this.sConf.auth.token || '';
				let data = {
					status: 1,
					ordering: '-hot'
				}
				psMethod.syncAuthenticatorRequest('/admin/placeList/', 'GET', token, data).then(res => {
					console.log('加载商户', res);
					this.placeArray = res.resmsg
				})
			},
			/**
			 * 加载分类列表
			 */
			loadModeList(e = null) {
				let token = this.sConf.auth.token || '';
				let data = {
					parent: 0,
					status: 1,
					ordering: '-hot'
				}
				if (e) {
					data['parent'] = e
				}
				psMethod.syncAuthenticatorRequest('/admin/cargoMode/', 'GET', token, data).then(res => {
					console.log('加载商户', res);
					if (e) {
						this.minModeData = res.resmsg
					} else {
						this.maxModeData = res.resmsg
					}
				})
			},
			designLayout() {
				let window = uni.getWindowInfo();
				let wh = window.windowHeight;
				let query = uni.createSelectorQuery().in(this);
				query.select('.gl-body').boundingClientRect();
				query.select('.gl-footer').boundingClientRect();
				query.select('.gl-container').boundingClientRect();
				query.exec((res) => {
					this.swiperH = wh - Math.ceil(res[0].top) - Math.ceil(res[1].height) - 50;
					this.topH = wh - Math.ceil(res[2].top) - 30;
				});
			},

		}
	}
</script>

<style lang="scss" scoped>
	/* 表格垂直滚动 */
	.table-container {
		/* height: 400px; */
		overflow-y: auto;

		::v-deep .uni-table .table-head th {
			font-weight: bold;
			z-index: 2;
			background-color: #fff;
			position: -webkit-sticky;
			position: sticky;
			top: 0;
		}

		::v-deep .uni-table-scroll {
			overflow: visible;
		}
	}
</style>